package org.marketing.common;

import java.io.Serializable;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;

public class JpushContext {
	
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	JPushClient jpushClient;
	public JpushContext(String key , String secret) {
		jpushClient=new JPushClient(secret,key);
	}

	/**
	 * 向设备发消息
	 * @param deviceId
	 * @param msg
	 * @param title
	 */
	public PushResult pushForDevice(Serializable deviceId, String msg,String title) {
		PushPayload payload = buildPushObject_alias_message(
				cn.jpush.api.push.model.Message.newBuilder().setMsgContent(msg)
						.setTitle(title).build(),msg,(String) deviceId);
		try {
		 	PushResult msgResult = jpushClient.sendPush(payload);
		 	if (null != msgResult) {
		 		logger.info("msgResult.sendno======="+msgResult.sendno);
		 	} else {
		 		logger.info("无法获取数据");
		 	}
		 	return msgResult;
		} catch (Exception e) {
			logger.error("消息推送失败",e);
			e.printStackTrace();
			return null;
			
		}
	}
	
	/**
	 * @Title: buildPushObject_alias_message
	 * @Description: 发送给单个人或者指定的多个人
	 * @param @param alias
	 * @param @param message
	 * @param @return 设定文件
	 * @return PushPayload 返回类型
	 * @author BENJAMIN
	 * @throws
	 */
	public static PushPayload buildPushObject_alias_message(cn.jpush.api.push.model.Message message,String content,
			String... alias) {
		return PushPayload.newBuilder().setPlatform(Platform.all())
				.setAudience(Audience.registrationId(alias))
				.setNotification(Notification.newBuilder().setAlert(content).addPlatformNotification(IosNotification.newBuilder().setSound("sound.caf").build()).build())
				.setOptions(Options.newBuilder().setApnsProduction(true).build())
				.setMessage(message).build();
	}
}
